<template>
  <doc-alert title="代码生成（单表）" url="/devdoc/new-feature/" />
  <doc-alert title="代码生成（树表）" url="/devdoc/new-feature/tree/" />
  <doc-alert title="代码生成（主子表）" url="/devdoc/new-feature/master-sub/" />
  <doc-alert title="单元测试" url="/devdoc/unit-test/" />

  <!-- 搜索 -->
  <ContentWrap>
    <el-form
      ref="queryFormRef"
      :inline="true"
      :model="queryParams"
      class="-mb-15px"
      label-width="68px"
    >
      <el-form-item label="表名称" prop="tableName">
        <el-input
          v-model="queryParams.tableName"
          class="!w-240px"
          clearable
          placeholder="请输入表名称"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表描述" prop="tableComment">
        <el-input
          v-model="queryParams.tableComment"
          class="!w-240px"
          clearable
          placeholder="请输入表描述"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          v-model="queryParams.createTime"
          :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
          class="!w-240px"
          end-placeholder="结束日期"
          start-placeholder="开始日期"
          type="daterange"
          value-format="YYYY-MM-DD HH:mm:ss"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="handleQuery">
          <Icon class="mr-5px" icon="ep:search" />
          搜索
        </el-button>
        <el-button @click="resetQuery">
          <Icon class="mr-5px" icon="ep:refresh" />
          重置
        </el-button>
        <el-button v-hasPermi="['infra:codegen:create']" type="primary" @click="openImportTable()">
          <Icon class="mr-5px" icon="ep:zoom-in" />
          导入
        </el-button>
        <el-button
          v-hasPermi="['infra:codegen:generate']"
          type="primary"
          @click="handleGenTableBatch()"
          :loading="isGenerateCodeBatchLoading"
        >
          <Icon class="mr-5px" icon="ep:zoom-in" />
          批量生成
        </el-button>
        <el-button
          v-hasPermi="['infra:codegen:generate']"
          type="primary"
          @click="handleDownloadMenuSql()"
          :loading="isDownloadSqlLoading"
        >
          <Icon class="mr-5px" icon="ep:download" />
          下载菜单SQL
        </el-button>
      </el-form-item>
    </el-form>
    <!-- 多选搜集器 -->
    <div class="selected-content">
      <el-form-item label="已选列表">
        <el-select
          v-model="collectIdList"
          multiple
          :max-collapse-tags="2"
          collapse-tags
          collapse-tags-tooltip
          @remove-tag="handleRemoveTag"
          placeholder="请选择要批量生成的列表项"
          class="content-select !w-240px"
        >
          <el-option
            v-for="item in collectIdOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
    </div>
  </ContentWrap>

  <!-- 列表 -->
  <ContentWrap>
    <el-table
      ref="selectTable"
      v-loading="loading"
      :data="list"
      @selection-change="handleSelectionChange"
      :row-key="getRowKeys"
    >
      <el-table-column type="selection" :reserve-selection="true" width="55" />
      <el-table-column align="center" label="数据源">
        <template #default="scope">
          {{
            dataSourceConfigList.find((config) => config.id === scope.row.dataSourceConfigId)?.name
          }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="表名称" prop="tableName" width="200" />
      <el-table-column
        :show-overflow-tooltip="true"
        align="center"
        label="表描述"
        prop="tableComment"
        width="200"
      />
      <el-table-column align="center" label="实体类名称" prop="className" width="200" />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="创建时间"
        prop="createTime"
        width="180"
      />
      <el-table-column
        :formatter="dateFormatter"
        align="center"
        label="更新时间"
        prop="createTime"
        width="180"
      />
      <el-table-column align="center" fixed="right" label="操作" width="360px">
        <template #default="scope">
          <el-button
            v-hasPermi="['infra:codegen:preview']"
            link
            type="primary"
            @click="handlePreview(scope.row)"
          >
            预览
          </el-button>
          <el-button
            v-hasPermi="['infra:codegen:update']"
            link
            type="primary"
            @click="handleUpdate(scope.row.id)"
          >
            编辑
          </el-button>
          <el-button
            v-hasPermi="['infra:codegen:delete']"
            link
            type="danger"
            @click="handleDelete(scope.row.id)"
          >
            删除
          </el-button>
          <!-- <el-button
            v-hasPermi="['infra:codegen:update']"
            link
            type="primary"
            @click="handleSyncDB(scope.row)"
          >
            同步
          </el-button> -->
          <el-button
            v-hasPermi="['infra:codegen:download']"
            link
            type="primary"
            @click="handleDownloadTable(scope.row)"
          >
            下载代码
          </el-button>
          <el-button
            v-hasPermi="['infra:codegen:generate']"
            link
            :disabled="isGenerateCodeLoading"
            type="primary"
            @click="handleGenTable(scope.row)"
          >
            生成代码
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>

  <!-- 弹窗：导入表 -->
  <ImportTable ref="importRef" @success="getList" />
  <!-- 弹窗：预览代码 -->
  <PreviewCode ref="previewRef" />
</template>
<script lang="ts" setup>
import { dateFormatter } from '@/utils/formatTime'
import download from '@/utils/download'
import * as CodegenApi from '@/api/infra/codegen'
import * as DataSourceConfigApi from '@/api/infra/dataSourceConfig'
import ImportTable from './ImportTable.vue'
import PreviewCode from './PreviewCode.vue'

defineOptions({ name: 'InfraCodegen' })

const message = useMessage() // 消息弹窗
const { t } = useI18n() // 国际化
const { push } = useRouter() // 路由跳转

const loading = ref(true) // 列表的加载中
const total = ref(0) // 列表的总页数
const list = ref([]) // 列表的数据
const queryParams = reactive({
  pageNo: 1,
  pageSize: 10,
  tableName: undefined,
  tableComment: undefined,
  createTime: []
})
const queryFormRef = ref() // 搜索的表单
const dataSourceConfigList = ref<DataSourceConfigApi.DataSourceConfigVO[]>([]) // 数据源列表
const selectTable: any = ref<HTMLElement | null>(null)
/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    const data = await CodegenApi.getCodegenTablePage(queryParams)
    list.value = data.list
    total.value = data.total
  } finally {
    loading.value = false
  }
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNo = 1
  getList()
}

const getRowKeys = (row) => {
  //  唯一标识
  return row.id
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value.resetFields()
  handleQuery()
}

/** 导入操作 */
const importRef = ref()
const openImportTable = () => {
  importRef.value.open()
}

/** 编辑操作 */
const handleUpdate = (id: number) => {
  push('/codegen/edit?id=' + id)
}

/** 预览操作 */
const previewRef = ref()
const handlePreview = (row: CodegenApi.CodegenTableVO) => {
  previewRef.value.open(row.id)
}

/** 删除按钮操作 */
const handleDelete = async (id: number) => {
  try {
    // 删除的二次确认
    await message.delConfirm()
    // 发起删除
    await CodegenApi.deleteCodegenTable(id)
    message.success(t('common.delSuccess'))
    // 刷新列表
    await getList()
  } catch {}
}

/** 同步操作  */
const handleSyncDB = async (row: CodegenApi.CodegenTableVO) => {
  // 基于 DB 同步
  const tableName = row.tableName
  try {
    await message.confirm('确认要强制同步' + tableName + '表结构吗?', t('common.reminder'))
    await CodegenApi.syncCodegenFromDB(row.id)
    message.success('同步成功')
  } catch {}
}

/** 下载代码操作 */
const handleDownloadTable = async (row: CodegenApi.CodegenTableVO) => {
  const res = await CodegenApi.downloadCodegen(row.id)
  download.zip(res, 'codegen-' + row.className + '.zip')
}

/** 生成代码操作 */
const isGenerateCodeLoading = ref(false)
const handleGenTable = async (row: CodegenApi.CodegenTableVO) => {
  // 二次确认
  await message.confirm(
    '生成代码时将重新编译系统, 预计等待2-5分钟, 确定该操作吗?',
    t('common.reminder')
  )

  isGenerateCodeLoading.value = true
  try {
    await CodegenApi.apiGenerateCodegen(row.id)
  } catch (error) {
  } finally {
    isGenerateCodeLoading.value = false
  }
}

// 选择的id
interface Item {
  value: number | string
  label: string
}
const collectIdList = ref<number[]>([])
const collectIdOptions = ref<Item[]>([])
const handleSelectionChange = (selectedList) => {
  const listData: number[] = []
  const optData: Item[] = []
  selectedList.forEach((item) => {
    listData.push(item.id)
    optData.push({
      value: item.id,
      label: item.classComment
    })
  })
  collectIdList.value = listData
  collectIdOptions.value = optData
}
// 批量生成
const isGenerateCodeBatchLoading = ref(false)
const handleGenTableBatch = async () => {
  console.log(collectIdList.value, '跨页批量选中的数据')
  if (collectIdList.value.length === 0) {
    message.warning('未选择任何列表项')
    return
  }

  // 二次确认
  await message.confirm(
    '生成代码时将重新编译系统, 预计等待2-5分钟, 确定该操作吗?',
    t('common.reminder')
  )

  isGenerateCodeBatchLoading.value = true
  try {
    await CodegenApi.apiGenerateCodegenBatch({
      list: collectIdList.value
    })
  } catch (error) {
  } finally {
    isGenerateCodeBatchLoading.value = false
  }
}

const isDownloadSqlLoading = ref(false)
const handleDownloadMenuSql = async () => {
  console.log(collectIdList.value, '跨页批量选中的数据')
  if (collectIdList.value.length === 0) {
    message.warning('未选择任何列表项')
    return
  }
  // 二次确认
  await message.confirm('即将下载菜单SQL, 确定该操作吗?', t('common.reminder'))
  isDownloadSqlLoading.value = true
  try {
    let res = await CodegenApi.apiDownloadMenuSql({
      list: collectIdList.value
    })
    let fileName = res.headers['content-disposition'].split(';')[1].split('=')[1]
    downloadFile(res.data, fileName)
  } catch (error) {
  } finally {
    message.error('下载失败!')
    isDownloadSqlLoading.value = false
  }
}

const downloadFile = (content, fileName) => {
  const blob = new Blob([content], { type: 'application/octet-stream;charset=UTF-8' })
  // 生成可下载的URL
  let href = URL.createObjectURL(blob)
  const downloadElement = document.createElement('a')
  downloadElement.href = href
  downloadElement.download = fileName // 下载后文件名
  document.body.appendChild(downloadElement)
  downloadElement.click() // 点击下载
  document.body.removeChild(downloadElement) // 下载完成移除元素
  window.URL.revokeObjectURL(href) // 释放掉blob对象
  message.success('下载成功！')
}

const handleRemoveTag = (tag) => {
  console.log('tags删除前回调', tag)
  const row = list.value.find((item) => item.id === tag)
  console.log('tags删除后回调', row)
  if (row) {
    selectTable.value.toggleRowSelection(row, false)
  }
}

/** 初始化 **/
onMounted(async () => {
  await getList()
  // 加载数据源列表
  dataSourceConfigList.value = await DataSourceConfigApi.getDataSourceConfigList()
})
</script>

<style lang="scss" scoped>
.selected-content {
  margin-top: 10px;

  .content-select {
    :deep(.el-input.el-input--default.is-disabled.el-input--suffix) {
      .el-input__wrapper {
        background-color: unset;
      }

      .el-input__suffix {
        display: none;
      }
    }
  }
}
</style>
